package com.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dao.CardDAO;
import com.dao.ErrorCardDao;
import com.dao.StaffDAO;
import com.dao.UserInfoDAO;
import com.pojo.Dictionary;
import com.pojo.*;
import com.util.StringUtil;
import com.util.ValidateHelper;
import com.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Description:
 * @Auther: tz
 * @Date: 2023/11/9 10:48
 */
@Service
public class UserInfoService extends ServiceImpl<UserInfoDAO, UserInfo> {

    @Autowired
    private UserInfoDAO userInfoDAO;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private CardDAO cardDAO;

    @Autowired
    private AlertService alertService;

    @Autowired
    private ErrorCardDao errorCardDao;

    @Autowired
    private StaffDAO staffDAO;

    public IPage<UserInfoVo> selectStaffByCard(String name, int page, int limit, String cardStatus){
        if(StringUtil.isNull(name)) {
            name = null ;
        }
        if(StringUtil.isNull(cardStatus)) {
            cardStatus = null;
        }
        IPage<UserInfoVo> staffList = userInfoDAO.selectStaffByCard(new Page(page, limit), name, 1, cardStatus) ;
        return staffList ;
    }

    /**
     * 解除卡绑定关系
     * @param id
     * @return
     */
    public String resetCard(String id){
        UserInfo staff = userInfoDAO.selectById(id) ;
        if(staff == null) {
            return "用户不存在" ;
        }
        if(StringUtil.isNull(staff.getCardNo())) {
            return "用户未绑定卡" ;
        }
        List<Card> cards = cardDAO.selectList(new QueryWrapper<Card>().eq("xuliehao" , staff.getCardNo())) ;
        if(cards.size() == 0) {
            return "卡信息不存在" ;
        }
        String cardNo = staff.getCardNo() ;
        String pin = staff.getPin() ;
        userInfoDAO.clearCard(id) ;
        Card card = cards.get(0) ;
        ErrorCard errorCard = new ErrorCard() ;
        errorCard.setCardNo(cardNo);
        errorCard.setMiyao(card.getMiyao());
        errorCard.setPin(pin);
        errorCard.setCtime(new Date());
        errorCardDao.insert(errorCard) ;
        cardDAO.deleteById(card) ;
        return null ;
    }

    /**
     * 卡与用户绑定
     * @param uid
     * @param cid
     * @return
     */
    public String bangdin(String uid , String cid){
        List<ErrorCard> errorCards = errorCardDao.selectList(new QueryWrapper<ErrorCard>().eq("card_no" , cid)) ;
        if(errorCards.size() == 0) {
            return "未找到卡信息" ;
        }
        UserInfo staff = userInfoDAO.selectById(uid) ;
        if(staff == null) {
            return "用户不存在" ;
        }
        if(StringUtil.isNotNull(staff.getCardNo())) {
            return "用户已经绑定卡" ;
        }
        ErrorCard errorCard = errorCards.get(0) ;
        Card card = new Card() ;
        card.setPin1(errorCard.getPin());
        card.setMiyao(errorCard.getMiyao());
        card.setStaffId(uid);
        card.setXuliehao(errorCard.getCardNo());
        card.setLuRuCreateTime(new Date());
        card.setStatus(1);
        cardDAO.insert(card) ;
        staff.setPin(errorCard.getPin());
        staff.setCardNo(errorCard.getCardNo());
        userInfoDAO.updateById(staff) ;
        errorCardDao.deleteById(errorCard) ;
        return null ;
    }

    /**
     * 卡与用户绑定
     * @param cid
     * @return
     */
    public String bangdin1(String cid){
        List<ErrorCard> errorCards = errorCardDao.selectList(new QueryWrapper<ErrorCard>().eq("card_no" , cid)) ;
        if(errorCards.size() == 0) {
            return "未找到卡信息" ;
        }
        ErrorCard errorCard = errorCards.get(0) ;
        Card card = new Card() ;
        card.setPin1(errorCard.getPin());
        card.setMiyao(errorCard.getMiyao());
        card.setXuliehao(errorCard.getCardNo());
        card.setLuRuCreateTime(new Date());
        card.setStatus(1);
        cardDAO.insert(card) ;
        errorCardDao.deleteById(errorCard) ;
        return null ;
    }

    public int getStaffByCard(String cardNo,String id) {
        List<Card> cardList = cardDAO.selectList(new QueryWrapper<Card>().eq("xuliehao" , cardNo)) ;
        List<UserInfo> staffList = userInfoDAO.selectList(new QueryWrapper<UserInfo>().eq("card_no" , cardNo)) ;
        // 白卡
        if (ValidateHelper.isEmptyCollection(cardList) && ValidateHelper.isEmptyCollection(staffList)) {
            return 0;
        }
        if(ValidateHelper.isNotEmptyCollection(cardList)) {
            UserInfo staff = userInfoDAO.selectById(cardList.get(0).getStaffId()) ;
            if (staff == null) {
                return 1;
            }
            // 正常
            return 2 ;
        }else{
            return 1;
        }
    }

    /**
     * 校验用户编号是否正确
     * @param id
     * @return
     */
    public String checkBh(String id){
        UserInfo staff = userInfoDAO.selectById(id) ;
        if (!staff.getBh().matches("^[A-Z]{2}\\d[\\S\\s]*?")){
            return "编号有问题，无法制卡" ;
        }
        if (staff.getCstime().startsWith("00")) {
            return "会员出生日期为0000/00/00，无法制卡" ;
        }
        if (ValidateHelper.isEmptyString(staff.getPicture())) {
            return "会员头像为空，无法制卡" ;
        }
        if (ValidateHelper.isEmptyString(staff.getName())) {
            return "会员姓名为空，无法制卡" ;
        }
        List<Alert> alertList = alertService.getAlertByStaff(staff.getId());
        if (ValidateHelper.isNotEmptyCollection(alertList)) {
            return alertList.get(0).getContent();
        }
        return "" ;
    }

    /**
     * 根据卡号获取用户信息
     * @param cardNo 卡号
     * @return
     */
    public Map<String,Object> getStaffInfoByCz(String cardNo, String queryStr){
        Map<String,Object> resultMap = new HashMap<String,Object>();
        QueryWrapper<Card> query = new QueryWrapper();

        List<String> zyNameList = new ArrayList<String>();
        if (ValidateHelper.isNotEmptyString(queryStr)) {
            List<Dictionary> zyList = new ArrayList<Dictionary>();
            if ("gs".equals(queryStr)) {
                zyList = dictionaryService.getDicByZyGs();
            }else if ("jt".equals(queryStr)) {
                zyList = dictionaryService.getDicByZyJt();
            }
            if (ValidateHelper.isNotEmptyCollection(zyList)) {
                for (Dictionary dictionary : zyList) {
                    if (ValidateHelper.isNotEmptyString(dictionary.getName())) {
                        zyNameList.add(dictionary.getName());
                    }
                }
            }
        }
        if (StringUtil.isNotNull(cardNo)){
            query.eq("xuliehao",cardNo);
            query.last("limit 1");
            Card card = cardDAO.selectOne(query);
            if (null != card) {
                resultMap.put("cardStatus",getCardStatus(card.getStatus()));
                Staff staff = new Staff();
                if (ValidateHelper.isNotEmptyString(queryStr)) {
                    staff = staffDAO.selectOne(new QueryWrapper<Staff>().eq("id",card.getStaffId()).in("zhiye", zyNameList).last("limit 1"));
                }else {
                    staff = staffDAO.selectById(card.getStaffId());
                }
                if (null != staff){
                    resultMap.put("staff",staff);
                    if (null == staff.getCardBalance()) {
                        resultMap.put("balance",0);
                    }else {
                        resultMap.put("balance",staff.getCardBalance());
                    }
                }
            }else {
                List<Staff> staffs = staffDAO.selectList(new QueryWrapper<Staff>().eq("card_no",cardNo));
                if (staffs.size() <= 0) {
                    return resultMap;
                }else {
                    resultMap.put("staff",staffs.get(0));
                }
            }
        }
        return resultMap;
    }

    private String getCardStatus(Integer status) {
        if (status == 1) {
            return "启用";
        }else if (status == 2){
            return "停用";
        }else if (status == 3){
            return "挂失";
        }else {
            return "报废";
        }
    }

    public UserInfo getStaffByCardNo(String cardNo) {
        List<UserInfo> staffList = userInfoDAO.selectList(new QueryWrapper<UserInfo>().eq("card_no" , cardNo)) ;
        if (staffList.size() > 0) {
            return staffList.get(0);
        }
        return null;
    }

    /**
     * 分页查询未开卡会员
     * @param page
     * @param limit
     * @param name
     * @return
     */
    public IPage<UserInfo> selectUserInfoByWkk(int page, int limit , String name){
        Page p = new Page(page , limit) ;
        QueryWrapper<UserInfo> query = new QueryWrapper() ;
        if(StringUtil.isNotNull(name)) {
            query.and(q -> {
                q.like("name" , "%"+name+"%").or().like("bh","%"+name+"%").or().like("phone","%"+name+"%").or().like("sfz","%"+name+"%") ;
            }) ;
        }
        //审核状态为已审核
        query.eq("shstatus",1);
        //未制卡
        query.eq("zk_flag",0);
        query.and(q -> {
            q.isNull("card_no").or().eq("card_no" , "") ;
        });
        IPage<UserInfo> iPage = userInfoDAO.selectPage(p,query) ;
        return iPage ;
    }

    /**
     * 分页查询会员
     * @param name
     * @param page
     * @param limit
     * @param zhiye
     * @return
     */
    public IPage userInfoList(String name,int page,int limit,String zhiye){
        Page p = new Page(page,limit);
        QueryWrapper<UserInfo> q = new QueryWrapper();
        if (StringUtil.isNotNull(zhiye)){
            q.eq("zhiye",zhiye);
        }
        if (StringUtil.isNotNull(name)){
            q.eq("bh",name).or().eq("phone",name).or().like("name","%"+name+"%");
        }
        q.orderByDesc("create_time");
        IPage iPage = userInfoDAO.selectPage(p,q);
        return iPage;
    }

    /**
     * 根据证件号查询会员数量
     * @param sfz   证件号
     * @return
     */
    public int sfzCount(String sfz){
        return userInfoDAO.selectList(new QueryWrapper<UserInfo>().eq("sfz",sfz)).size();
    }
}
